import fs from 'fs-extra';
import AdmZip from 'adm-zip';

import path from 'path';
import getServerInfo from '../../src/lib/System/getServerInfo';
import FSTool from '../../src/lib/FSTool';

async function installDependencies() {
    let inPkgEXE = __dirname.includes('snapshot');

    const serverInfo = await getServerInfo();

    const npmAssets = [
        {name: 'sqlite3', path: 'sqlite3-5.17'}
    ];

    for (let i = 0; inPkgEXE && i < npmAssets.length; i++) {
        let appBasePath = path.dirname(process.execPath);
        let insidePath = path.join(__dirname, '../../');
        const npmName = npmAssets[i].name;
        const npmPath = npmAssets[i].path;
        // 安装依赖
        const sysDevDependenciesPath = path.join(appBasePath, `node_modules/${npmName}`);
        let npmZipPath;
        if (serverInfo.operatingSystem === 'Windows_NT') {
            npmZipPath = path.join(insidePath, `assets/devDependencies/${npmPath}/win-x86/${npmName}.zip`);
        } else if (serverInfo.operatingSystem === 'Linux' && serverInfo.arch === 'x64') {
            npmZipPath = path.join(insidePath, `assets/devDependencies/${npmPath}/linux-x86/${npmName}.zip`);
        } else if (serverInfo.operatingSystem === 'Linux' && serverInfo.arch === 'arm64') {
            npmZipPath = path.join(insidePath, `assets/devDependencies/${npmPath}/linux-arm64/${npmName}.zip`);
        }

        fs.ensureDirSync(sysDevDependenciesPath);
        const zip = new AdmZip(npmZipPath);
        const zipEntries = zip.getEntries();
        const zipFileList = zipEntries
            .map((zipEntry: any) => JSON.parse(zipEntry.toString()))
            .filter((zipFile: any) => !zipFile.isDirectory);

        if (FSTool.getFilePathList(sysDevDependenciesPath).length !== zipFileList.length) {
            console.log(`系统未安装 ${npmName} 依赖组件，正在安装中...`);
            fs.removeSync(sysDevDependenciesPath);
            zip.extractAllTo(sysDevDependenciesPath, true);
            console.log(`${npmName} 依赖组件，安装完成`);
        }
    }


}

export default installDependencies;
